package scala.basic

import scala.util.control.Breaks
import scala.util.control.Breaks.{break, breakable}

/**
 * for 循环测试类
 */
case object ForTest {

  def main(args: Array[String]): Unit = {

    println("--------------范围数据循环(to)---------------")
    for (i <- 1 to 3) println("i=" + i)
    println("--------------范围数据循环(until)---------------")
    for (i <- 1 until 3) println("i=" + i)
    println("--------------循环守卫---------------")
    for (i <- 1 to 3 if i != 2) println("i=" + i)
    println("--------------循环步长---------------")
    for (i <- 1 to 10 by 2) println("i=" + i)
    println("--------------循环嵌套---------------")
    for (i <- 1 to 3; j <- 1 to 3) println("i:" + i + "j:" + j)
    println("--------------循环嵌套引入变量---------------")
    for (i <- 1 to 3; j = 4 - i) println("i=" + i + "j=" + j)
    println("--------------循环嵌套引入变量推导---------------")
    for {i <- 1 to 3; j = 4 - i} {
      println("i=" + i + "j=" + j)
    }
    println("--------------循环返回值---------------")
    var res = for (i <- 1 to 3) yield i
    println(res)
    println("--------------循环返回值案例实操---------------")
    var res1 = for (i <- 1 to 10) yield (i * 2)
    println(res1)
    println("--------------倒叙打印---------------")
//    for (i <- 1 to 10 reverse) print(i)
    println()
    println("--------------异常跳出循环---------------")
    try {
      for (i <- 1 to 10) {
        println(i)
        if (i == 5) throw new RuntimeException
      }
    } catch {
      case e =>
    }
    println("正常结束循环")
    println("----------------采用scala自带的函数，退出循环-----------------")
    //  2.采用scala自带的函数，退出循环
    Breaks.breakable(for (i <- 1 to 10) {
      println(i)
      if (i == 5) Breaks.break();
    })
    println("正常结束循环")
    Breaks.tryBreakable(
      try {
        for (i <- 1 to 10) {
          println(i)
          if (i == 5) throw new RuntimeException
        }
      } catch {
        case e =>
      }
    )
    println("正常结束循环")
    println("-------------对break省略---------------")
    breakable {
      for (i <- 1 to 10) {
        println(i)
        if (i == 5) break;
      }
    }
    println("正常结束循环")
    println("--------------循环遍历10以内的所有数据，奇数打印，偶数跳过-----------")
    breakable {
      for (i <- 1 to 10) {
        if (i % 2 == 1) {
          println(i)
        } else {
          println("contionue")
        }
      }
    }
    println("程序正常结束")
    println("--------------99乘法表-----------")
    for (i <- 1 to 10; j <- 1 to i) println(i + "*" + j + "=" + (i * j))
    println("--------------99除法表-----------")
    for (i <- 1 to 10; j <- 1 to i) println(i + "/" + j + "=" + (i / j))
    println("--------------99加法表-----------")
    for (i <- 1 to 10; j <- 1 to i) println(i + "+" + j + "=" + (i + j))
    println("--------------99减法表-----------")
    for (i <- 1 to 10; j <- 1 to i) println(i + "-" + j + "=" + (i - j))
  }
}
